//
// Created by 麻再挺 on 2021/12/9.
//

#include "cycle_queue.h"


/**
 * 初始化队列
 */
Status Cycle_Queue_Init(CQQueue *queue) {
    // 构造一个空队列
    queue->base = malloc(MAXSIZE * sizeof(CQQueue));
    // 存储分配失败
    if (!queue->base) exit(OVERFLOW);
    queue->front = queue->rear = 0;
    return OK;
}

/**
 * 销毁队列
 */
Status Cycle_Queue_Destroy(CQQueue *queue) {
    queue->front = queue->rear = 0;
    free(queue->base);
    return OK;
}

/**
 * 清空队列
 */
Status Cycle_Queue_Clear(CQQueue *queue) {
    // 获取队列长度
    int length = Cycle_Queue_Length(queue) + + queue->front;
    for (int i = queue->front + 0; i < length; ++i) {
        int tmp = i;
        if (i >= MAXSIZE) {
            tmp = i % MAXSIZE;
        }
        queue->base[tmp] = 0;
    }
    queue->rear = queue->front;
    return OK;
}

/**
 * 判断队列是否为空
 */
Status Cycle_Queue_Empty(CQQueue *queue) {
    return Cycle_Queue_Length(queue) == MAXSIZE;
}

/**
 * 队列长度
 */
int Cycle_Queue_Length(CQQueue *queue) {
    return (queue->rear - queue->front + MAXSIZE) % MAXSIZE;
}

/**
 * 获取队列头
 * @param queue 队列
 * @param elem 元素
 * @return
 */
Status Cycle_Queue_GetHead(CQQueue *queue, CQElemType *elem) {
    *elem = queue->base[queue->front];
    return OK;
}

/**
 * 入队
 * @param queue 队列
 * @param elem 数据
 * @return
 */
Status Cycle_Queue_Enter(CQQueue *queue, CQElemType elem) {
    // 判断队列是否已满
    if ((queue->rear + 1) % MAXSIZE == queue->front) return ERROR;
    // 赋值
    queue->base[queue->rear] = elem;
    queue->rear = (queue->rear + 1) % MAXSIZE;
    return OK;
}

/**
 * 出队
 * @param queue 队列
 * @param elem 元素
 * @return
 */
Status Cycle_Queue_Deter(CQQueue *queue, CQElemType *elem) {
    // 判断队列是否已满
    if (queue->front == queue->rear) return ERROR;
    *elem = queue->base[queue->front];
    queue->front = (queue->front + 1) % MAXSIZE;
    return OK;
}

/**
 * 队列打印
 * @param queue 队列
 */
void Cycle_Queue_Print(CQQueue *queue) {
    // 获取队列长度
    int length = Cycle_Queue_Length(queue) + + queue->front;
    for (int i = queue->front + 0; i < length; ++i) {
        int tmp = i;
        if (i >= MAXSIZE) {
            tmp = i % MAXSIZE;
        }
        printf("%d", queue->base[tmp]);
        if (i < length - 1) {
            printf(", ");
        }
    }
    printf("\n");
}